const mongoose = require('mongoose');

/**
 * 面相分析记录模型
 * 用于存储用户的面相分析历史记录
 */

// 定义面部特征子模式
const FacialFeatureSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    description: '面部特征名称'
  },
  description: {
    type: String,
    required: true,
    description: '面部特征描述'
  }
}, { _id: false });

// 定义面相分析记录模式
const FaceAnalysisSchema = new mongoose.Schema({
  // 关联的用户ID
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true,
    description: '关联的用户ID'
  },
  
  // 分析的图片URL
  imageUrl: {
    type: String,
    required: true,
    description: '分析的面部图片URL'
  },
  
  // 整体评分 (0-100)
  overallScore: {
    type: Number,
    required: true,
    min: 0,
    max: 100,
    description: '整体面相评分'
  },
  
  // 整体印象
  overallImpression: {
    type: String,
    required: true,
    description: '整体面相印象描述'
  },
  
  // 面部特征分析
  facialFeatures: {
    faceShape: {
      type: FacialFeatureSchema,
      required: true,
      description: '脸型分析'
    },
    eyebrows: {
      type: FacialFeatureSchema,
      required: true,
      description: '眉毛分析'
    },
    eyes: {
      type: FacialFeatureSchema,
      required: true,
      description: '眼睛分析'
    },
    nose: {
      type: FacialFeatureSchema,
      required: true,
      description: '鼻子分析'
    },
    lips: {
      type: FacialFeatureSchema,
      required: true,
      description: '嘴唇分析'
    }
  },
  
  // 性格特质
  personalityTraits: {
    type: [{
      type: String,
      required: true
    }],
    required: true,
    description: '性格特质列表'
  },
  
  // 职业建议
  careerAdvice: {
    type: String,
    required: true,
    description: '职业发展建议'
  },
  
  // 感情建议
  relationshipAdvice: {
    type: String,
    required: true,
    description: '感情关系建议'
  },
  
  // 健康建议
  healthRecommendations: {
    type: String,
    required: true,
    description: '健康养生建议'
  },
  
  // 幸运颜色
  luckyColor: {
    type: String,
    required: true,
    description: '幸运颜色'
  },
  
  // 幸运数字
  luckyNumber: {
    type: Number,
    required: true,
    min: 1,
    max: 9,
    description: '幸运数字'
  },
  
  // 分析时间
  analysisTime: {
    type: Date,
    default: Date.now,
    description: '分析时间'
  },
  
  // 保存时间
  savedAt: {
    type: Date,
    default: Date.now,
    description: '保存时间'
  }
}, {
  timestamps: true // 自动添加createdAt和updatedAt字段
});

// 创建索引以提高查询性能
FaceAnalysisSchema.index({ userId: 1, createdAt: -1 });
FaceAnalysisSchema.index({ overallScore: 1 });

// 在保存前更新savedAt字段
FaceAnalysisSchema.pre('save', function(next) {
  if (this.isModified()) {
    this.savedAt = new Date();
  }
  next();
});

// 创建并导出模型
const FaceAnalysis = mongoose.model('FaceAnalysis', FaceAnalysisSchema);

module.exports = FaceAnalysis;